package com.csf.project.service.impl;

import com.csf.project.mapper.UserMapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.csf.project.entity.User;
import com.csf.project.service.AuthService;
import com.csf.project.service.UserService;

import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {


    private static final String TOKEN_SECRET = "sWeZcLrAeBt";
    private static final String TOKEN_ISSUER = "wzlab";
    private static final String TOKEN_ROLE = "role";

    @Value("${app.password.algorithmName}")
    private String algorithmName = "md5";
    @Value("${app.password.hashIterations}")
    private int hashIterations = 2;
    
    @Autowired
    private UserService userService;




    @Override
    public String encodePassword(String account, String password) {
        return new SimpleHash(algorithmName, password, getSalt(account), hashIterations).toHex();
    }

    private String getSalt(String account) {
        return account;
    }

    @Override
    public String encodeToken(String account, String role) {
        Algorithm algorithm = null;
        algorithm = Algorithm.HMAC256(TOKEN_SECRET);
        assert algorithm != null;
        return JWT.create()
                .withIssuer(TOKEN_ISSUER)
                .withSubject(account)
                .withClaim(TOKEN_ROLE, role)
                .sign(algorithm);
    }

    private DecodedJWT decodeToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer(TOKEN_ISSUER)
                    .build();
            return verifier.verify(token);
        } catch (JWTVerificationException exception){
            throw new AuthenticationException("Invalid token");
        }
    }

    @Override
    public String decodeTokenAccount(String token) {
        return decodeToken(token).getSubject();
    }

    @Override
    public String decodeTokenRole(String token) {
        return decodeToken(token).getClaim(TOKEN_ROLE).asString();
    }

    @Override
    public User login(String username, String password) {
        User example = new User();
        example.setUsername(username);
        User found = userService.findUser(example);
        if (found == null) return null;
        String encoded = this.encodePassword(found.getUsername(), password);
        if (!found.getPassword().equals(encoded)) return null;
        String accesstoken = this.encodeToken(found.getUsername(), found.getRole());
        SecurityUtils.getSubject().login(new UsernamePasswordToken(accesstoken, accesstoken));
        found.setAccesstoken(accesstoken);
        return found;
    }

}
